import React, { useImperativeHandle, forwardRef } from "react";
import AdminModal from "../AdminModal/index.tsx";
import DetailView from "../DetailView/index.tsx";
import type { DetailFieldConfig } from "../../global.ts";

interface DetailModalProps {
  detailConfig: DetailFieldConfig[];
  detailComponent?: React.ComponentType<{ data: any }>;
  modalWidth?: number;
}

export interface DetailModalHandles {
  show: (data: any) => void;
}

const DetailModal = forwardRef<DetailModalHandles, DetailModalProps>(
  ({ detailConfig, detailComponent:DetailComponent, modalWidth }, ref) => {
    const [showDetail, setShowDetail] = React.useState(false);
    const [data, setData] = React.useState({});

    useImperativeHandle(ref, () => ({
      show: (data: any) => {
        setShowDetail(true);
        setData(data);
      },
    }));

    const handleOk = () => {
      setShowDetail(false);
    };

    return (
      <AdminModal
        isVisible={showDetail}
        title="详情"
        onCancel={() => setShowDetail(false)}
        onOk={() => handleOk()}
        modalWidth={modalWidth}
      >
        {DetailComponent ? (
          <DetailComponent data={data} />
        ) : (
          <DetailView detailFieldConfig={detailConfig} data={data} />
        )}
      </AdminModal>
    );
  }
);

export default DetailModal;
